<?php
class Media extends AppModel{
    public $useTable  = 'media';
    public $lang_code = 'vn';
    
    
    function add($data = array())
    {
        $this->save($data);
		return $this->getLastInsertId();
    }
    
    function get_media($status = "")
    {
        $status = $status == "all" ? '' : 'AND media.`status` = 1';
    	$lang_code = $this->lang_code;
        $sql = "SELECT media.*, media_desc.*, image.`name`
				FROM media_desc, media
                LEFT JOIN image ON media.media_id = image.post_id AND image.type = 'media' AND image.`status` = 1
				WHERE media.media_id = media_desc.media_id $status AND media_desc.lang_code = '$lang_code' 
				ORDER BY media.sort_order, media_desc.title";

		return $this->query($sql);
    }
    
    function del($media_id = "")
    {
    	$sql = "DELETE FROM media WHERE media_id = '$media_id'";
    	$this->query($sql);
    	$sql = "DELETE FROM media_desc WHERE media_id = '$media_id'";
    	$this->query($sql);
        $sql = "DELETE FROM image WHERE post_id = '$media_id' AND type = 'media'";
    	$this->query($sql);
        
    	return 1;
    }
    
    public function get_media_by_id($media_id = "", $lang = '')
    {
    	if($media_id == "")
    		return null;
    	$lang_code = $this->lang_code;

    	$where_lang = "AND media_desc.lang_code = '$lang_code'";
    	if($lang == 'all')
    		$where_lang = "";

    	$result = array();
    	$sql = "SELECT * FROM media WHERE media_id = '$media_id'";
    	$data = $this->query($sql);
    	if(!empty($data))
    	{
    		$result['media'] = $data[0]['media'];
    	}
    	else
    	{
    		$result['media'] = array();
    	}
    	

    	$sql = "SELECT * 
				FROM  media_desc 
				WHERE media_id = '$media_id' $where_lang ";
		$data = $this->query($sql);
		$media_desc = array();
		foreach ($data as $value) {
			$lang_code = $value['media_desc']['lang_code'];
			$media_desc[$lang_code] = $value['media_desc'];

		}
		$result['media_desc'] = $media_desc;
		return $result;
    }
    
    function edit($media_id = "", $data = array())
    {
		return $this->updateAll(
		    $data, 
		    array('media_id' => $media_id)
		);
    }
    
    function change_status($media_id = "")
    {
    	$sql = "SELECT * FROM media WHERE media_id = '$media_id'";
        $data = $this->query($sql);
        if(!empty($data))
        {
            $status = $data[0]['media']['status'];
            $change_status = $status == 1 ? '0' : '1';
            $sql = "UPDATE media SET status = '$change_status' WHERE media_id = '$media_id'";
            $this->query($sql);
            return $change_status;
        }
        return -1;
    }
}